<?php
namespace frontend\widget;


use frontend\models\GoodsCategory;
use yii\base\Widget;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

class CateListWidget extends Widget
{
    public $cate_id=1;

    public $categorys=[];

    public function run()
    {
        $this->getCategorys();

        $categorys = $this->getSon($this->cate_id);
        $html = '';
        foreach ($categorys as $key=>$cate){
            //得到子分类
            $sons = $this->getSon($cate['id']);
            $child='';
            foreach ($sons as $son){
                $sonUrl = Url::to(['shop/list','goods_category_id'=>$son['id']]);
                $child.='<li><a href="'.$sonUrl.'">'.$son['name'].'</a></li>';
            }
            if($key==0){
                $status = 'on';
                $status2='';
            }else{
                $status='';
                $status2='none';
            }

            $html.='<div class="child"><h3 class="'.$status.'"><b></b>'.$cate['name'].'</h3><ul class="'.$status2.'">'.$child.'</ul></div>';
        }
        return '<div class="catlist_wrap">'.$html.'</div><div style="clear:both; height:1px;"></div>';

    }

    public function getCategorys(){
        //找到当前分类
        $current_cate=GoodsCategory::findOne(['id'=>$this->cate_id]);
        //找到当前分类和它的子分类
        $son_cates =GoodsCategory::find();
        $categorys = $son_cates->andWhere(['>','lft',$current_cate->lft])->andWhere(['<','rgt',$current_cate->rgt])->asArray()->all();
        $this->categorys=$categorys;
        return $categorys;

    }

    public function getSon($parent_id){
        $son=[];
        foreach ($this->categorys as $cate){
            if($cate['parent_id']==$parent_id){
                $son[] = $cate;
            }

        }
        return $son;
    }
}

